﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Peninsula.Common.Exceptions;
using Peninsula.DataAccess.POCO;

namespace Peninsula.Account.Manager
{
    public  class RoleManager:ManagerBase
    {
        public virtual void Add(Role role)
        {
            ValidateData(role);
            RoleProvider.Insert(role);
        }

        public virtual void Delete(string roleName)
        {
            RoleProvider.Delete(r => r.RoleName == roleName);
        }
        public virtual void Delete(Expression<Func<Role, bool>> predicate)
        {
            RoleProvider.Delete(predicate);
        }

        public virtual Role Get(string roleName)
        {
            return RoleProvider.Get(r => r.RoleName == roleName);
        }

        /// <summary>
        /// 通过管理员ID获取他的角色名称的第一个
        /// </summary>
        /// <param name="AdminId"></param>
        /// <returns></returns>
        public virtual Role GetByAdminId(string AdminId)
        {
            return RoleProvider.Get(r => r.Admins.Where(a => a.Id == AdminId).First().Id == AdminId);
        }
        public virtual Role Get(Expression<Func<Role, bool>> predicate)
        {
            return RoleProvider.Get(predicate);
        }

        public virtual IEnumerable<Role> All()
        {
            return RoleProvider.Entities;
        }

        public virtual void Update(Role role)
        {
            ValidateData(role, false);
            RoleProvider.Update(role);
        }

        #region Permissions

        public virtual IEnumerable<Permission> GetAllPermissions(string roleName)
        {
            return RoleProvider.Get(r => r.RoleName == roleName).Permissions.AsEnumerable();
        }

        #endregion

        private void ValidateData(Role role, bool isCreating = true)
        {
            List<DataViolationItem> violations = new List<DataViolationItem>();

            if (isCreating && RoleProvider.Get(r => r.RoleName == role.RoleName) != null)
            {
                violations.Add(new DataViolationItem("RoleName", role.RoleName, "角色名已存在"));
            }
            if (!isCreating && RoleProvider.Get(r => r.RoleName == role.RoleName && r.Id != role.Id) != null)
            {
                violations.Add(new DataViolationItem("RoleName", role.RoleName, "角色名已存在"));
            }

            if (violations.Count > 0)
            {
                throw new DataViolationException(violations);
            }
        }
    }
}
